package AdminService

import (
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/grand"
	"time"
)

func ChangePass(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	oldPassword := r.GetString("oldPassword")
	newPassword := r.GetString("newPassword")
	newPassword2 := r.GetString("newPassword2")
	if newPassword != newPassword2 {
		return response.FailByRequestMessage(r, "二次密码不一致")
	}
	adminModel := (*entity.Admin)(nil)
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "admin").Where("id", req.AdminId).Struct(&adminModel)
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	if adminModel == nil {
		return response.FailByRequestMessage(r, "登录过期，请重新登录")
	}
	if tools.EncryptPassword(oldPassword, adminModel.PasswordSalt) != adminModel.Password {
		// 记录错误登陆日志，后面做封IP处理
		return response.FailByRequestMessage(nil, "请输入正确的旧密码")
	}
	// 验证通过
	passwordSalt := grand.Letters(10)
	_, err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "admin").Where("id", req.AdminId).Update(g.Map{
		"password_salt": passwordSalt,
		"password":      tools.EncryptPassword(newPassword, passwordSalt),
		"updated_at":    time.Now().Unix(),
	})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return response.SuccessByRequestMessage(nil, "成功")
}
